package com.kavenka.zhufengfm.app.fragments.discover;


import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.widget.ListView;
import android.widget.TextView;
import com.kavenka.zhufengfm.app.Constants;
import com.kavenka.zhufengfm.app.R;
import com.kavenka.zhufengfm.app.adapter.DiscoverCategoryAdapter;
import com.kavenka.zhufengfm.app.client.DataParse;
import com.kavenka.zhufengfm.app.modle.DiscoverCategory;
import com.kavenka.zhufengfm.app.provider.DatabaseContract;
import com.kavenka.zhufengfm.app.tasks.TaskCallBack;
import com.kavenka.zhufengfm.app.tasks.TaskResult;
import com.kavenka.zhufengfm.app.tasks.discover.DiscoverCategoryTask;
import com.kavenka.zhufengfm.app.utils.MyLog;
import org.json.JSONObject;

import java.util.LinkedList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class DiscoverCategoryFragment extends Fragment implements TaskCallBack {

    private DiscoverCategoryAdapter adapter;

    public DiscoverCategoryFragment() {
        // Required empty public constructor
    }

    private LinkedList<DiscoverCategory> categoryList;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        categoryList=new LinkedList<DiscoverCategory>();
        ContentResolver resolver=getActivity().getContentResolver();
        Cursor cursor = resolver.query(
                DatabaseContract.DiscoverCategories.CONTENT_URI,
                null,
                null,
                null,
                DatabaseContract.DiscoverCategories.ORDER_NUM+" ACS"
        );
        if (cursor != null) {
            while (cursor.moveToNext()){
                DiscoverCategory category=new DiscoverCategory();
                category.parserCursor(cursor);
                categoryList.add(category);
            }
            cursor.close();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_discover_category, container, false);

        ListView listView= (ListView) view.findViewById(R.id.discover_category_listView);
        adapter = new DiscoverCategoryAdapter(getActivity(),categoryList);
        listView.setAdapter(adapter);

        DiscoverCategoryTask task=new DiscoverCategoryTask(this);
        task.execute();
        return view;
    }

    /**
     * 在异步任务中设置的回调，当异步下载结束回调这个方法
     * @param result
     */
    @Override
    public void onTaskFinished(TaskResult result) {
        if (result != null) {
            int action=result.action;
            switch (action){
                case Constants.TASK_ACTION_DISCOVER_CATEGORY:
                    upSetCategory((JSONObject)result.data);
                    break;
            }
        }
    }

    /**
     * 加载数据
     * @param data
     */
    private void upSetCategory(JSONObject data) {
        if (data != null) {
            List<DiscoverCategory> categories= DataParse.parserDisciverCater(data);
            if (categories != null) {
                categoryList.clear();
                categoryList.addAll(categories);
                adapter.notifyDataSetChanged();
                //保存从网络获取的数据
                saveDiscoverCategory(categories);
            }

        }
    }

    /**
     * 保存数据到contentprovider
     * @param categories
     */
    private void saveDiscoverCategory(List<DiscoverCategory> categories) {
        if (categories != null) {
            ContentResolver resolver = getActivity().getContentResolver();
            for (DiscoverCategory discoverCategory : categories) {
                try {
                    resolver.insert(
                            DatabaseContract.DiscoverCategories.CONTENT_URI,
                            discoverCategory.prepareValues()
                    );
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
